Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.

For example:
Given the below binary tree,

  1. 1
  2. / \
  3. 2 3

Return 6.

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. int max = Integer.MIN_VALUE;
  12. public int maxPathSum(TreeNode root) {
  13. helper(root);
  14. return max;
  15. }
  16. int helper(TreeNode root) {
  17. if (root == null) return 0;
  18. int left = Math.max(helper(root.left), 0);
  19. int right = Math.max(helper(root.right), 0);
  20. max = Math.max(max, root.val + left + right);
  21. return root.val + Math.max(left, right);
  22. }
  23. }